package cn.sunlight.mm.wx.controller;

import cn.sunlight.framework.annotation.HmComponent;
import cn.sunlight.framework.annotation.HmRequestMapping;
import cn.sunlight.framework.annotation.HmSetter;
import cn.sunlight.mm.base.BaseController;
import cn.sunlight.mm.entity.Result;
import cn.sunlight.mm.pojo.WxMember;
import cn.sunlight.mm.utils.DateUtils;
import cn.sunlight.mm.wx.service.WxMemberService;
import cn.sunlight.mm.wx.utils.WxUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sunlight
 * @description: 会员控制器
 * @date 2021/5/31
 * @Version v1.0
 */
@HmComponent
@Slf4j
public class MemberController extends BaseController {

    @HmSetter("memberService")
    private WxMemberService memberService;

    /**
     * 用户授权登录，未查询到添加用户信息到数据库
     * @param request
     * @param response
     * @throws Exception
     */
    @HmRequestMapping("/member/login")
    public void login (HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            Map<String,String> mapData = parseJSON2Object(request, HashMap.class);
            log.debug("mapData: {}",mapData);

            //获取参数
            String code = mapData.get("code"); //登录凭证
            String encryptedData = mapData.get("encryptedData"); //加密数据
            String iv = mapData.get("iv"); //解密参数

            //根据微信工具类获取openId和sessionkey
            JSONObject jsonObject = WxUtil.get(code);
            log.debug("微信工具类获取openId和sessionkey wx:{}",jsonObject);

            String openId = jsonObject.getString("openid"); //openId在我们这里类似webSession来使用
            String sessionKey = jsonObject.getString("session_key");

            //根据service提供的方法完成登录与注册
            WxMember wxUser = memberService.findWxMemberByOpenId(openId);
            if (wxUser==null){
                //如果数据库中有该用户数据就登录，如果没有就需要解密数据并添加到数据库进行注册
                //sessionKey解密用户数据利用微信工具类
                JSONObject userJson = WxUtil.getUserInfo(encryptedData, sessionKey, iv);
                log.debug("微信工具类解密用户数据 userInfo：{}",userJson);

                wxUser=new WxMember();
                wxUser.setNickName(userJson.getString("nickName"));
                wxUser.setAvatarUrl(userJson.getString("avatarUrl"));
                wxUser.setGender(userJson.getString("gender"));
                wxUser.setCity(userJson.getString("city"));
                wxUser.setProvince(userJson.getString("province"));
                wxUser.setCountry(userJson.getString("country"));
                wxUser.setLanguage(userJson.getString("language"));
                wxUser.setOpenId(userJson.getString("openId"));
                wxUser.setUnionId(userJson.getString("unionId"));
                wxUser.setCreateTime(DateUtils.parseDate2String(new Date()));

                log.debug("调用service，保存会员数据 wxUser: {}",wxUser);

                //调用微信用户服务，执行新增操作
                memberService.add(wxUser);
            }

            //调用service获取
            Map map=new HashMap();
            map.put("token",openId);
            map.put("userInfo",wxUser);

            printResult(response,new Result(true,"登录成功",map));
        }catch (RuntimeException e){
            e.printStackTrace();
            log.error("",e);
            printResult(response,new Result(false,"登录失败"+e.getMessage()));
        }
    }

    /**
     * 更新用户城市及学科方向
     * @param request
     * @param response
     * @throws Exception
     */
    @HmRequestMapping("/member/updateCityCourse")
    public void updateCityCourse (HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            Map<String,String> mapData=parseJSON2Object(request,HashMap.class);
            log.debug("mapData:{}",mapData);

            String openId = getHeaderAuthorization(request);
            mapData.put("openId",openId);
            log.debug("updateCityCourse mapData:{}",mapData);

            memberService.updateCityCourse(mapData);

            printResult(response,new Result(true,"更新成功"));
        }catch (RuntimeException e){
            e.printStackTrace();
            log.error("updateCityCourse",e);
            printResult(response,new Result(false,"更新失败"+e.getMessage()));
        }
    }

}
